/*
 * Project: push-center-service-impl
 * 
 * File Created at 2014-10-10
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package com.greenline.push.service.core.tmpl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import com.greenline.push.core.pushcenter.AppTemplateManager;
import com.greenline.push.dal.pushcenter.dataobject.AppTemplateDO;
import com.greenline.push.service.core.utils.Constants;

/**
 * 模板信息和外部渠道对应关系的缓存类
 * 
 * @author weirui.shenwr
 * @date 2014-10-10
 * @version V1.0
 */
public class AppTemplateCache {
    @Resource
    private AppTemplateManager appTemplateManager;
    private static final String SPLITS = "%";
    /**
     * templateId对应的渠道配置【list内元素按优先级高-->低排序】结构[templateId%domainId-->
     * appTemplateInfo]
     */
    private Map<String, List<AppTemplateInfo>> data = new ConcurrentHashMap<String, List<AppTemplateInfo>>();
    private Logger log = Constants.LOG_CACHE;

    @SuppressWarnings("unused")
    private void initial() {
        log.info("AppTemplateCache initial start=====");

        List<AppTemplateDO> templateList = appTemplateManager.listByExample(null);

        // config
        warpConfig(templateList);
        sortMap();
        log.info("AppTemplateCache initial end=====");
    }

    /**
     * 重新加载模板配置
     */
    public boolean reload() {
        log.info("reload app tempalte cache start======");
        // list初始化默认2个长度
        try {
            List<AppTemplateDO> templateList = appTemplateManager.listByExample(null);

            if (null != templateList) {
                data.clear();
                warpConfig(templateList);
                sortMap();
            }
            log.info("reload app tempalte cache end======");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("reload app tempalte cache exception======" + e.getMessage());
            return false;
        }

    }

    public List<AppTemplateInfo> get(Long templateId, Long domainId) {
        return data.get(templateId + SPLITS + domainId);
    }

    public List<AppTemplateInfo> get(String templateId, String domainId) {
        return data.get(templateId.trim() + SPLITS + domainId.trim());
    }

    private void convertDo(AppTemplateDO tmp, AppTemplateInfo template) {
        // 有问题的数据 比如没有priority,直接跳过
        if (null != tmp.getPriority()) {
            template.setPriority(tmp.getPriority());
            template.setAppId(tmp.getAppId());
            template.setExtTemplId(tmp.getExtTemplId());
            template.setExtTemplType(tmp.getExtTemplType());
            template.setParamConvert(tmp.getParamConvert());
            template.setTemplateId(tmp.getTemplateId());
            template.setAppTemplateId(tmp.getId());
            template.setAppChannelId(tmp.getAppChannelId());
        } else {
            log.error(String.format("appTemplateCache转换遇到没有优先级数据.templateid:%s,apptemplateId:%s", tmp.getTemplateId(), tmp.getId()));
        }

    }

    private void warpConfig(List<AppTemplateDO> templateList) {
        for (AppTemplateDO tmp : templateList) {
            String key = tmp.getTemplateId() + SPLITS + tmp.getDomainId();
            if (data.containsKey(key)) {
                AppTemplateInfo template = new AppTemplateInfo();
                convertDo(tmp, template);
                data.get(key).add(template);
            } else {
                List<AppTemplateInfo> atemplateinfoList = new ArrayList<AppTemplateInfo>();
                AppTemplateInfo template = new AppTemplateInfo();
                convertDo(tmp, template);
                atemplateinfoList.add(template);
                data.put(key, atemplateinfoList);
            }
        }
    }

    private void sortMap() {
        for (Entry<String, List<AppTemplateInfo>> entry : data.entrySet()) {
            Collections.sort(entry.getValue());
        }
    }
}
